package com.flowerplus.store.common.data.http;

import android.content.Context;

import com.flowerplus.store.Logger;
import com.flowerplus.store.R;
import com.flowerplus.store.common.data.http.interceptor.LoggerInterceptor;
import com.flowerplus.store.common.data.http.interceptor.NetWorkInterceptor;
import com.flowerplus.store.common.data.utils.ui.ResourcesUtil;
import com.google.gson.GsonBuilder;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by ems on 2017/2/27.
 * 网络帮助类
 */

public class HttpHelp {
    Context mContext;

    public static final String serverCerStr = "";
    private OkHttpClient mOkHttpClient;
    private Retrofit mRetrofit;

    public HttpHelp(Context context) {
        mContext = context.getApplicationContext();
    }

    public OkHttpClient getOkHttpClient() {
        //添加自定义请求证书才需要
//        if (mOkHttpClient == null) {
//            HttpsUtils.SSLParams sslParams = null;
//            try {
//                InputStream serverCer = new Buffer().writeUtf8(serverCerStr).inputStream();
//                InputStream clientBks = mContext.getAssets().open("client.bks");
//                //初始化https证书参数信息
//                sslParams = HttpsUtils.getSslSocketFactory(new InputStream[]{serverCer}, clientBks, "im_cms");
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
            mOkHttpClient = new OkHttpClient.Builder().connectTimeout(150, TimeUnit.SECONDS)
                    .writeTimeout(150, TimeUnit.SECONDS).readTimeout(150, TimeUnit.SECONDS)
                    .addInterceptor(new NetWorkInterceptor())
                    .addInterceptor(new LoggerInterceptor("OkHttp", true))
                    .hostnameVerifier(new HttpsUtils.UnSafeHostnameVerifier())
//                    .sslSocketFactory(sslParams.sSLSocketFactory, sslParams.trustManager)
                    .build();
//        }
        Logger.d("httpHelp", mOkHttpClient.hashCode() + "");
        return mOkHttpClient;
    }

    public Retrofit getRetrofit(OkHttpClient okHttpClient, ResourcesUtil resourcesUtil) {
        if (mRetrofit == null) {
            String ipDefault = resourcesUtil.getString(R.string.ip_default);
            mRetrofit = new Retrofit.Builder().addConverterFactory(GsonConverterFactory.create(new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create()))
                    .baseUrl(ipDefault)
                    .client(okHttpClient)
                    .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                    .build();
        }
        return mRetrofit;
    }

}
